# -*- coding: utf-8 -*-
# 姓名:谚语
# 开发时间:2022/10/15 10:10
from flask import make_response, current_app
from flask_restful.utils import PY3
from json import dumps


# data 字典，code 未来返回给前端的状态码
def output_json(data, code, headers=None):
    """Makes a Flask response with a JSON encoded body"""

    # 此处添加自己定义的json格式规则  目的: 把返回个前端的数据做一个统一的封装，以便于前端可以使用统一的规则来得到数据
    if 'message' not in data:
        data = {
            # 'message': 'OK',
            'code': 20000,  # 自动把状态20000封装到json中
            'data': data
        }

    settings = current_app.config.get('RESTFUL_JSON', {})

    # If we're in debug mode, and the indent is not set, we set it to a
    # reasonable value here.  Note that this won't override any existing value
    # that was set.  We also set the "sort_keys" value.
    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', not PY3)

    # always end the json dumps with a new line
    # see https://github.com/mitsuhiko/flask/pull/1262
    # 将字典转换成json
    dumped = dumps(data, **settings) + "\n"

    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp
